package com.itheima.controller;

import com.itheima.config.AliyunOSSProperties;
import com.itheima.pojo.Result;
import com.itheima.util.AliyunOSSUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@RestController
public class UploadController {
    // 注意需要手动添加 https://
    // @Value: 读取application.properties等配置文件中的数据,给变量赋值
    // @Value("${aliyun.oss.endpoint}")
    // private String endpoint;
    // @Value("${aliyun.oss.bucketName}")
    // private String bucketName;

    @Autowired
    private AliyunOSSProperties aliyunOSSProperties;

    /**
     * 用户头像的文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public Result upload(MultipartFile file) throws Exception {
        log.info("aliyunOSSProperties = {}", aliyunOSSProperties);
        log.info("file = {}", file);

        // 原始文件名
        String originalFilename = file.getOriginalFilename();
        log.info("originalFilename = {}", originalFilename);

        // 文件名要唯一 = 时间戳 + 随机数 + 原始文件名
        String newFileName = System.currentTimeMillis() + "_" + UUID.randomUUID().toString() + "_" + originalFilename;

        // 把上传的文件移动到服务器本地目录
        // file.transferTo(new File("D:\\MyFileTest\\upload\\" + newFileName));

        // 上传到阿里云OSS
        String imageUrl = AliyunOSSUtils.upload(aliyunOSSProperties.getEndpoint(), aliyunOSSProperties.getBucketName(), file.getBytes(), newFileName);

        return Result.success(imageUrl);
    }
}
